<template>
  <!-- <v-page full> -->
  <div class="flex p-[8px] pb-[0] oms v-page" style="height: calc(100% - 52px); align-items: start">
    <div class="main mr-[2px]" id="v-page" ref="Vpage">
      <div id="anchors">
        <el-form :model="formData" :rules="rules" label-width="260" ref="policyInformation">
          <div class="section-box">
            <div class="formTitle v-anchor">策略信息</div>
            <FormStrategyInfo v-model="formData" :policy-information="policyInformation" />
          </div>

          <div class="section-box">
            <div class="formTitle v-anchor">订单信息</div>
            <FormOrderInfo v-model="formData" />
          </div>

          <div class="section-box">
            <div class="formTitle v-anchor">产品信息</div>
            <FormProductInfo :form-data="formData" />
          </div>

          <div class="section-box">
            <div class="formTitle v-anchor">收货地址信息</div>
            <FormShippingAddress :form-data="formData" />
          </div>

          <div class="section-box">
            <div class="formTitle v-anchor">仓库和运输方式</div>
            <FormStorehouseTrans :form-data="formData" />
          </div>

          <el-divider> 满足以上条件时，订单执行以下操作 </el-divider>

          <div class="section-box" style="margin-bottom: 0">
            <div class="formTitle v-anchor">订单排程和操作</div>
            <FormOrderScheduleOprea ref="formOrderScheduleOprea" :form-data="formData" />
          </div>
        </el-form>
      </div>
    </div>
    <div class="side-navigation">
      <div class="broadside">
        <div :class="['broadside-item cursor-pointer', index == sideActive ? 'active' : '']" v-for="(item, index) in sideNavigationData" :key="index" @click="scrollTop(index)">{{ item.label }}</div>
      </div>
      <div>
        <div class="mt-3 roll" :class="sideActive == 0 ? 'active' : ''" @click="toTop">
          <svg-icon class="text-white text-3xl" :icon-class="sideActive < 1 ? 'top' : 'top_on'"></svg-icon>
        </div>
        <div class="mt-3 roll" @click="toDown">
          <svg-icon class="text-white text-3xl" :icon-class="sideActive >= 5 ? 'down' : 'down_on'"></svg-icon>
        </div>
      </div>
    </div>
  </div>
  <div class="buttonBox">
    <el-button @click="handleCancel">取消</el-button>
    <el-button type="primary" @click="save">保存</el-button>
  </div>
  <Vtransport ref="transport" @confirm="transportConfirm"></Vtransport>
  <Vstash ref="stash"></Vstash>
  <!-- </v-page> -->
</template>
<script setup name="Edit">
import { nextTick, onMounted, reactive, toRefs } from "vue"
import FormStrategyInfo from "./components/strategyInfo"
import FormOrderInfo from "./components/orderInfo"
import FormProductInfo from "./components/productInfo"
import FormShippingAddress from "./components/shippingAddress"
import FormStorehouseTrans from "./components/storehouseTrans"
import FormOrderScheduleOprea from "./components/orderScheduleOprea"
import Vtransport from "../components/transport.vue"
import Vstash from "../components/stash.vue"
import "./index.scss"
import { useRouter, useRoute } from "vue-router"
import { cloneDeep } from "lodash"
import { ElMessage } from "element-plus"
import api from "../api"

// textarea 换行要处理的字段
const textareaFieldArray = ["order_no", "product_keyword", "receiving_province", "receiving_city", "address_keys"]
// 时间 开始结束 要处理的字段
const timerDispose = {
  strategy_time: ["strategy_start_time", "strategy_end_time"],
  order_pay_time: ["order_pay_start_time", "order_pay_end_time"],
}

const scrollTop = (index) => {
  nextTick(() => {
    let anchorElement = document.querySelectorAll(".section-box")[index]
    let offsetTop = anchorElement.offsetTop - 20
    Vpage.value.scrollTo({ top: offsetTop, behavior: "smooth" })
  })
}
import action from "@/utils/action.js"

const transport = ref()
const stash = ref()
const router = useRouter()
const route = useRoute()
const policyInformation = ref()
const Vpage = ref()
const data = reactive({
  formData: {
    strategy_time: [],
    strategy_name: "",
    priority: 0,
    is_shipping_rule: 0,
    order_source: "",
    platform_id: "",
    // shop_id: '',
    // site: '',
    shop_id: [],
    site: [],
    order_status: [],
    reason: [],
    order_pay_start_price: "",
    order_pay_end_price: "",
    order_pay_currency: "CNY", // 订单支付币种
    product_start_price: "",
    product_end_price: "",
    product_currency: "CNY", // 产品总额币种
    freight_start_price: "",
    freight_end_price: "",
    freight_currency: "CNY", // 运费币种
    strategy_description: "",
    original_shipping_method: [], // 订单原来的运输方式
    original_shipping_warehouse: [], // 订单原来的发货仓库
    customer_shipping_method: [], // 平台客户选择运输方式(包含)
    customer_shipping_method_exclude: [], // 平台客户选择运输方式（不包含）
    mark_shipping_status: "", // 标记发货状态
    order_priority: "", // 标记发货状态
    order_no: "", // 系统订单号
    receiving_province: "", // 州/省
    receiving_city: "", // 城市
    address_keys: "", // 详细地址关键词
    product_keyword: "", // 商品中文名包含关键词
    cancel_reason: "", // 取消原因
    cause_reason: "", // 问题订单
    logistics_rules: "", // 物流优选
    consignment_remark: "", // 设置礼品&发货订单备注
    change_order_status: "", // 取消原因
    in_tort: [], // 包含商品侵权风险
    ex_tort: [], // 不包含商品侵权风险
    status: 1, // 状态
    product_category: [], // 产品分类
    in_attribute: [], // 商品物流属性（包含）
    ex_attribute: [], // 商品物流属性（不包含）
    product_package_length: "", // 产品包装长
    product_package_width: "", // 产品包装宽
    product_package_height: "", // 产品包装高
    custom_perimeter: "", // 自定义周长
    product_start_purchase_price: "", // 产品总采购价 最低
    product_end_purchase_price: "", // 产品总采购价 最高
    product_start_volume_weight: "", // 订单体积重区间 start
    product_end_volume_weight: "", // 订单体积重区间 end
    product_start_volume: "", // 订单产品总体积 start
    product_end_volume: "", // 订单产品总体积 end
    product_start_weight: "", // 订单产品总重量 start
    product_end_weight: "", // 订单产品总重量 end
    product_status: "", // 商品状态
    sku_start_number: "", // 产品SKU总数量区间 最低
    sku_end_number: "", // 产品SKU总数量区间 最高
    product_start_number: "", // 产品数量区间 最高
    product_end_number: "", // 产品数量区间 最低
    is_registered: "", // 运输方式 1
    transport_type: "", // 运输方式 2
    shipping_method: "", // 运输方式 3
    strategy_time: [],
    order_pay_time: [],
    platform_order_type: {
      amazon: [],
      ebay: [],
    },
    in_zip_code: [["", ""]],
    ex_zip_code: [["", ""]],
    receiving_country: [],
  },
  sideNavigationData: [{ label: "策略信息" }, { label: "订单信息" }, { label: "产品信息" }, { label: "收货地址信息" }, { label: "仓库和运输方式" }, { label: "订单排程操作" }],
  changeOrderStatus: [],
  shippingRule: [],
  orderPriority: [],
  markShippingStatus: [],
  isRegistered: [],

  scrollNode: null,
  scrollNodeY: null,
  parentNode: null,
  anchorsList: [],
  sideActive: 1,
})
let { formData, changeOrderStatus, shippingRule, orderPriority, markShippingStatus, isRegistered, sideNavigationData, sideActive, scrollNode, scrollNodeY, parentNode, anchorsList } = toRefs(data)
const rules = reactive({
  strategy_name: [
    {
      required: true,
      message: "不能为空",
      trigger: "blur",
    },
  ],
  strategy_time: [
    {
      required: true,
      message: "不能为空",
      trigger: "change",
    },
  ],
  order_pay_time: [
    {
      required: true,
      message: "不能为空",
      trigger: "change",
    },
  ],
})
onMounted(() => {
  nextTick(() => {
    scrollNode.value = document.getElementById("v-page")
    scrollNodeY.value = scrollNode.value.getBoundingClientRect().y - 1
    parentNode.value = document.getElementById("anchors")
    Vpage.value.addEventListener("scroll", handleScroll)
    update()
  })
})
// onBeforeUnmount(() => {
//   Vpage.value.removeEventListener("scroll", handleScroll)
// })
import keepAliveStore from "@/store/modules/keepalive"
const keepStore = keepAliveStore()
const routerName = router.currentRoute.value.name
watch(
  () => keepStore.currentKeepAliveList,
  (val) => {
    if (!val.includes(routerName)) {
      Vpage.value.removeEventListener("scroll", handleScroll)
    }
  }
)

//滚动到底部
const toDown = () => {
  Vpage.value.scrollTo({ top: Vpage.value.scrollHeight, behavior: "smooth" })
}
//滚动到顶部
const toTop = () => {
  Vpage.value.scrollTo({ top: 0, behavior: "smooth" })
}
const handleScroll = () => {
  let index = sideActive.value
  sideActive.value = anchorsList.value.findIndex((d) => d.getBoundingClientRect().y > scrollNodeY.value)
  // if (index === 6 && sideActive.value === 0) {
  //   sideActive.value = 6
  // }
}
const update = () => {
  nextTick(() => {
    if (!parentNode.value) return
    anchorsList.value = Array.from(parentNode.value.querySelectorAll(".v-anchor"))
    handleScroll()
  })
}
//运输方式返回值
const transportConfirm = (val) => {}
//提交数据
const save = async () => {
  const { id } = route.query
  const dtd = cloneDeep(formData.value)

  Object.keys(dtd).forEach((key) => {
    if (textareaFieldArray.includes(key)) {
      dtd[key] = dtd[key].split("\n").map((line) => line.trim())
    }
    if (timerDispose[key]) {
      dtd[timerDispose[key][0]] = dtd[key][0]
      dtd[timerDispose[key][1]] = dtd[key][1]
      delete dtd[key]
    }

    // 蜜汁操作，问后端。
    if (key === "platform_order_type") {
      console.error("dtd[key]", dtd[key])
      const { amazon, ebay } = dtd[key]
      const ra = []
      if (amazon) ra.concat(amazon)
      if (ebay) ra.concat(amazon)
      dtd[key] = [...ra]
    }
    let priceKey = ["order_pay_start_price", "order_pay_end_price", "product_start_price", "product_end_price", "freight_start_price", "freight_end_price"]
    priceKey.forEach((k) => {
      dtd[key] = dtd[key] == "" ? null : dtd[key]
    })

    // if (!dtd[key]) {
    //   dtd[key] = ""
    // }
  })
  dtd.order_source = dtd.order_source || dtd.order_source == 0 ? dtd.order_source : ""
  // console.log(dtd)
  // return

  dtd.change_order_status = dtd.change_order_status || ""
  let res
  if (!id || route.path.includes("/add")) {
    delete dtd.id
    delete dtd.exec_order_num
    res = await api.create(dtd)
  } else {
    res = await api.update(dtd, id)
  }
  const { message } = res
  if (message.indexOf("已存在") > -1) return
  ElMessage({
    message: `${id ? "修改" : "新增"}成功！`,
    type: "success",
  })
  handleCancel()
  // router.push(`/order-strategy/scheduling-strategy`)
}
const handleCancel = () => {
  action.setGlobalState({
    // changeMicoTabsPath: {
    //   type: 'closeActiveTab',
    // }
    changeMicoTabsPath: {
      type: "closeTab",
    },
  })
  router.push(`/order-strategy/scheduling-strategy`)
}

const formOrderScheduleOprea = ref()
const initFormData = async () => {
  const route = useRoute()
  const { id } = route.query
  if (!id) return
  const res = await api.apiGetOrderStrategy(id)
  const resData = res.data
  resData.strategy_time = [resData["strategy_start_time"], resData["strategy_end_time"]]
  resData.order_pay_time = [resData["order_pay_start_time"], resData["order_pay_end_time"]]
  Object.keys(resData).forEach((key) => {
    if (textareaFieldArray.includes(key) && Array.isArray(resData[key])) {
      resData[key] = resData[key].join("\n")
    }
  })
  data.formData = res.data
  setTimeout(() => {
    if (!formOrderScheduleOprea?.value) return
    formOrderScheduleOprea?.value?.shippingWarehousechange(data.formData.shipping_warehouse)
  }, 1000)
}

onMounted(() => {
  initFormData()
})
</script>
<style lang="scss" scoped>
.formTitle {
  padding-left: 6px;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  // color: #0a1431;
  position: relative;

  &::before {
    content: "";
    left: 0;
    position: absolute;
    //bottom: 0;
    display: inline-block;
    background-color: #3366f1;
    width: 3px;
    top: 50%;
    margin-top: -8px;
    left: -6px;
    height: 14px;
    vertical-align: -2px;
  }
}

:deep(.v-page__body) {
  background-color: #fafafa;
}

:deep(.input) {
  width: 400px;
}

.w100 {
  width: 100%;
}

.flex {
  align-items: center;
}

.warn {
  width: 25px;
  height: 20px;
}

.skuBox {
  width: 300px;
  min-height: 100px;
  border: 1px solid #c0c4cc;
  border-radius: 5px;
  margin-top: 10px;
  padding: 5px 10px;
  max-height: 300px;
  overflow: auto;
  cursor: pointer;

  p {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.inline-label {
  :deep(.el-form-item__label) {
    width: 125px !important;
  }
}

.buttonBox {
  text-align: center;
  box-shadow: 0 0 10px #f0f4fe;
  padding: 10px 0;
  // background-color: #fff;
  background-color: var(--base-color);
  margin: 0 8px;
  box-shadow: 0px -3px 6px 0px rgba(51, 102, 241, 0.1);
  position: relative;
}

:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}

:deep(.el-input__inner) {
  line-height: 1px !important;
}

:deep(.el-form-item) {
  .el-form-item {
    margin-bottom: 10px;
    margin-right: 20px;
  }
}

.labelButton {
  position: absolute;
  top: -35px;
  z-index: 55;
  left: 372px;
  font-size: 14px;
  color: #f00;
  letter-spacing: 1px;
}

// .postcode {
//   background: #fff;
//   padding: 10px;
//   width: 600px;
//   :deep(.el-form-item__content) {
//     display: unset;
//   }
// }

.start {
  :deep(.el-form-item__content) {
    align-items: start;
  }
}

.main {
  overflow: auto;
  height: 100%;
  // margin: 10px;
  // background-color: #fff;
  flex-flow: row nowrap;
  width: 100%;
  border-radius: 5px;
}

.el-step.is-vertical {
  :deep(.el-step__line) {
    width: 1px !important;
    top: 3px;
    background-color: #e6e7e9;
  }

  :deep(.el-step__title) {
    font-size: 14px;
  }

  :deep(.is-process) {
    font-weight: initial;
    color: #9da1ad;
  }
}

.scroll {
  margin-top: 35px;
  margin-left: -10px;

  .svg-icon {
    width: 35px;
    height: 35px;
    cursor: pointer;
  }
}

.side-navigation {
  width: 200px;
  margin-right: 8px;
  border-radius: 5px;
}

.broadside {
  width: 100%;
  padding: 8px;
  padding-top: 24px;
  margin-right: 8px;
  // background-color: #fff;
  background-color: var(--base-color);
  font-size: 14px;
}
.broadside-item {
  padding: 0 10px 28px 14px;
  position: relative;
  &::before {
    content: "";
    display: inline-block;
    width: 7px;
    height: 7px;
    border-radius: 50%;
    border: 2px solid #e6e7e9;
    background-color: #ffffff;
    position: absolute;
    left: 1px;
    top: 9px;
    z-index: 9;
  }
  &::after {
    content: "";
    display: inline-block;
    width: 0px;
    height: 50px;
    border-left: 1px solid #e6e7e9;
    position: absolute;
    left: 4px;
    top: 12px;
  }
  &:nth-last-child(1)::after {
    content: "";
    display: inline-block;
    width: 0px;
    height: 50px;
    border-left: 0px solid #e6e7e9;
    position: absolute;
    left: 3px;
    top: 12px;
  }
}

.broadside-item.active {
  color: #3487ff;

  &::before {
    border: 2px solid #3366f1;
  }
}
</style>
